package com.qyhl.webtv.commonlib.utils.qiniu;


import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.entity.act.UploadImageBean;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * Created by helin on 2018/1/2.
 */
public class QiniuUpload {

    private final UploadManager uploadManager;
    private double maxPro;

    private List<UploadImageBean> uploadBeanList;

    private QiniuUpload() {

        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .zone(Zone.httpsAutoZone)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();
        uploadManager = new UploadManager(config);
    }

    public static QiniuUpload qiniuUpload = new QiniuUpload();

    public static QiniuUpload getQiniuUpload() {
        return qiniuUpload;
    }


    /**
     * 上传活动多个文件
     *
     * @param files
     * @param token
     * @param host
     * @param listener
     */
    public void UploadFiles(final List<UploadBean> files, String token, final String host, final UploadResultListener listener) {
        uploadBeanList = new ArrayList<>();
        final List<UploadBean> resultFiles = new ArrayList<>();
        maxPro = files.size();
        for (int i = 0; i < files.size(); i++) {
            UploadImageBean uploadImageBean = new UploadImageBean();
            uploadImageBean.setIndex(i);
            uploadBeanList.add(uploadImageBean);
            UploadFile(files.get(i), listener, new UploadListener() {
                @Override
                public void uploadSuccess(String path, int index, int postion, int type, String viewText, int viewId) {
                    UploadBean uploadBean = new UploadBean();
                    uploadBean.setPostion(postion);
                    if (host.startsWith("http")) {
                        uploadBean.setUrl(host + "/" + path);
                    } else {
                        uploadBean.setUrl("http://" + host + "/" + path);
                    }
                    uploadBean.setType(type);
                    uploadBean.setViewId(viewId);
                    uploadBean.setViewText(viewText);
                    uploadBean.setIndex(index);
                    resultFiles.add(uploadBean);
                    if (resultFiles.size() == files.size()) {
                        listener.uploadSuccess(resultFiles);
                    }
                }

                @Override
                public void uplaodError() {
                    listener.uplaodError();
                }
            }, token, i);
        }
    }

    /**
     * 上传文件
     *
     * @param uploadBean
     * @param viewListener
     * @param listener
     * @param token
     * @param index
     */
    private void UploadFile(UploadBean uploadBean, final UploadResultListener viewListener, final UploadListener listener, String token, final int index) {
        File file1 = new File(uploadBean.getPath());
        String key = UUID.randomUUID().toString();
        String prefix = file1.getName().substring(file1.getName().lastIndexOf(".") + 1);
        String fileName = key + "." + prefix;
        HashMap<String, String> par = new HashMap<>();
        //类型
        par.put("x:type", uploadBean.getType() + "");
        par.put("x:postion", uploadBean.getPostion() + "");
        par.put("x:index", index + "");

        //
        //自定view的文本
        par.put("x:viewText", uploadBean.getViewText() + "");
        //自定一View的Id
        par.put("x:viewId", uploadBean.getViewId() + "");
        uploadManager.put(uploadBean.getPath(), fileName, token, new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            int type = Integer.parseInt(res.optString("x:type"));
                            int index = Integer.parseInt(res.optString("x:index"));
                            int postion = Integer.parseInt(res.optString("x:postion"));
                            int viewId = Integer.parseInt(res.optString("x:viewId"));
                            String viewText = res.optString("x:viewText");
                            String path = res.optString("key");
                            listener.uploadSuccess(path, index, postion, type, viewText, viewId);
                        } else {
                            listener.uplaodError();
                        }
                    }
                },
                new UploadOptions(par, null, false,
                        new UpProgressHandler() {
                            @Override
                            public void progress(String key, double percent) {
                                double preCount = 0;
                                for (int i = 0; i < uploadBeanList.size(); i++) {
                                    UploadImageBean upb = uploadBeanList.get(i);
                                    if (upb.getIndex() == index) {
                                        upb.setPercent(percent);
                                    }
                                    preCount += upb.getPercent();
                                }
                                double preo = preCount / maxPro * 100;
                                viewListener.uploadPre(preo);
                            }
                        }, null));

    }

    public void upLoadImages(final List<String> pathList, String token, final String host, final UpImageLoadResultListener listener) {
        final List<String> resultFiles = new ArrayList<>();
        for (int i = 0; i < pathList.size(); i++) {
            upLoad(pathList.get(i), token, new UpImageLoadListener() {
                @Override
                public void uploadSuccess(String path, int position) {
                    if (host.startsWith("http")) {
                        path = host + path;
                    } else {
                        path = "http://" + host + path;
                    }
                    resultFiles.add(path);
                    if (resultFiles.size() == pathList.size()) {
                        listener.uploadSuccess(resultFiles);
                    }
                }

                @Override
                public void uplaodError() {
                    listener.uplaodError();
                }
            }, i);
        }
    }

    private void upLoad(String path, String token, final UpImageLoadListener listener, final int position) {
        File file = new File(path);
        String key = UUID.randomUUID().toString();
        String prefix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        String fileName = key + "." + prefix;
        uploadManager.put(path, fileName, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                if (info.isOK()) {
                    String path = response.optString("key");
                    listener.uploadSuccess(path, position);
                } else {
                    listener.uplaodError();
                }
            }
        }, null);
    }
}
